﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace VideoChatApp
{
    public partial class MainPage : UserControl
    {
        public VideoBrush webCamBrush;
        public ImageBrush capturedImage;
        CaptureSource captureSource;
        VideoCaptureDevice webCam;
        MemoryStreamAudioSink audioSink;
        public MainPage()
        {
            InitializeComponent();

        }

        void captureSource_CaptureImageCompleted(object sender, CaptureImageCompletedEventArgs e)
        {
            capturedImage.ImageSource = e.Result;
            
         //   MessageBox.Show("Image is captured");
        }

        void captureSource_CaptureFailed(object sender, ExceptionRoutedEventArgs e)
        {
            MessageBox.Show(string.Format("Failed to capture image: {0}", e.ErrorException.Message));
        }

        private void btnClick_Click(object sender, RoutedEventArgs e)
        {
            // message.Text = "You have clicked the button";
        }

        private void btnStartCam_Click(object sender, RoutedEventArgs e)
        {
            if (CaptureDeviceConfiguration.RequestDeviceAccess() && captureSource.VideoCaptureDevice != null)
            {    
                if(audioSink==null)
                {
                    audioSink = new MemoryStreamAudioSink();
                    audioSink.CaptureSource = captureSource;
                }
                //captureSource.Start();
                audioSink.CaptureSource.Start();
                liveTarget.Visibility = System.Windows.Visibility.Visible;
                liveTarget.UseLayoutRounding = true;
                //liveTarget.SetValue(null,captureSource.GetValue(null));
                //ProcessAudioStart();
            }
        }

        private void ProcessAudioStart()
        {
            bool ok = CaptureDeviceConfiguration.AllowedDeviceAccess;
            if(!ok)
            {
                ok = CaptureDeviceConfiguration.RequestDeviceAccess();
            }
            if (ok)
            {
                if(audioSink== null)
                {
                    CaptureSource source = new CaptureSource(){
                        AudioCaptureDevice = CaptureDeviceConfiguration.GetDefaultAudioCaptureDevice()
                    };
                    audioSink = new MemoryStreamAudioSink();
                    audioSink.CaptureSource = source;
                }
                audioSink.CaptureSource.Start();
            }
        }

        private void btnStopCam_Click(object sender, RoutedEventArgs e)
        {            
            if (captureSource.VideoCaptureDevice != null)
            {
               // captureSource.Stop();
                ProcessAudioStop();
            }
           
        }

        private void ProcessAudioStop()
        {
            audioSink.CaptureSource.Stop();
            if (!File.Exists(@"C:\temp\test.wav"))
                File.Create(@"C:\temp\test.wav");
            using (FileStream stream = File.OpenWrite("C:\\temp\\test.wav"))
            {
                byte[] wavFileHeader = WavFileHelper.GetWavFileHeader(audioSink.AudioData.Length,
                  audioSink.AudioFormat);

                stream.Write(wavFileHeader, 0, wavFileHeader.Length);

                // Now write the rest of the data...  
                byte[] buffer = new byte[4096];
                int read = 0;

                audioSink.AudioData.Seek(0, SeekOrigin.Begin);

                while ((read = audioSink.AudioData.Read(buffer, 0, buffer.Length)) > 0)
                {
                    stream.Write(buffer, 0, read);
                }
                stream.Flush();
                stream.Close();
            }
        }

        private void btnCapture_Click(object sender, RoutedEventArgs e)
        {
           // MessageBox.Show("Capturing Image");
            if (captureSource.VideoCaptureDevice != null && captureSource.State == CaptureState.Started)
            {
               // MessageBox.Show("Image is being captured");
                captureSource.CaptureImageAsync();
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            captureSource = new CaptureSource();
            captureSource.CaptureFailed += captureSource_CaptureFailed;
            captureSource.CaptureImageCompleted += captureSource_CaptureImageCompleted;
            capturedImage = new ImageBrush();
            webCam = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
            if (null != webCam)
            {
                captureSource.VideoCaptureDevice = webCam;
                webCamBrush = new VideoBrush();
                webCamBrush.SetSource(captureSource);
                webcamDisplay.Fill = webCamBrush;
                capturedDisplay.Fill = capturedImage;
            }
        }
    }
}
